from functools import wraps

from flask import request

from app.error import BusinessError


def require_json(error_415="请使用 JSON 格式请求", error_400="数据格式错误"):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not request.is_json:
                msg = error_415 or "Content-Type must be application/json"
                raise BusinessError(msg, 415)
            try:
                request.get_json()
            except Exception:
                msg = error_400 or "Invalid JSON data"
                raise BusinessError(msg, 400)

            return f(*args, **kwargs)

        return decorated_function

    return decorator
